package com.lovo.bbs.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.NamingException;

import com.lovo.bbs.po.BoardPo;
import com.lovo.bbs.util.DbUtil;
import com.lovo.bbs.util.MysqlDb;

/**
 * 板块Dao
 * 
 * @author tiancen2001
 * 
 */
public class BoardDao {
	 public static final int OPER_OF_INSERT=1;
	 public static final int OPER_OF_UPDATE=2;
	 public static final int OPER_OF_DELETE=3;
	 
	 public BoardDao(){
		 
	 }
	 
	/**
	 * 返回所有板块Po列表
	 * 
	 * @return
	 * @throws SQLException
	 * @throws NamingException
	 */
	public   ArrayList<BoardPo> getAllBoard() throws NamingException,
			SQLException {
		ArrayList<BoardPo> boardPos = new ArrayList<BoardPo>();

		MysqlDb mysqldb = new MysqlDb();
		mysqldb.setPool(true);
		Connection con = DbUtil.getConn(mysqldb);

		String sql = "select 	boardid, boardname from board ";
		ResultSet rs = con.prepareStatement(sql).executeQuery();
		while (rs.next()) {
			BoardPo tempPo = new BoardPo();
			tempPo.setBoardID(rs.getInt(1));
			tempPo.setBoardName(rs.getString(2));
			boardPos.add(tempPo);
		}
		mysqldb.closeRS(rs);
		mysqldb.closeConnection(con);
		return boardPos;
	}

	 /**
	  * 板块更新
	 * @throws SQLException 
	 * @throws NamingException 
	  */
	public   int updateBoard(BoardPo po, int operType) throws NamingException, SQLException {
		int  changed=0;
		
		MysqlDb mysqldb = new MysqlDb();
		mysqldb.setPool(true);
		Connection con = DbUtil.getConn(mysqldb);
		con.setAutoCommit(false);
		
		if(operType==BoardDao.OPER_OF_INSERT){//插入新板块
			String sqlInsert = "insert into board(boardname)values(?)";
			PreparedStatement ps = con.prepareStatement(sqlInsert);
			ps.setString(1, po.getBoardName());
			changed = ps.executeUpdate();
			mysqldb.closePS(ps);
		}else if(operType==BoardDao.OPER_OF_UPDATE){//更新板块名
			String sqlUpdate = "update board set boardname=? where boardid=?";
			PreparedStatement ps = con.prepareStatement(sqlUpdate);
			ps.setString(1, po.getBoardName());
			ps.setInt(2, po.getBoardID());
			changed = ps.executeUpdate();
			mysqldb.closePS(ps);
		}else if(operType==BoardDao.OPER_OF_DELETE){//删除板块
			String sqlDelete = "delete from board where boardid=?";
			PreparedStatement ps = con.prepareStatement(sqlDelete);
			ps.setInt(1, po.getBoardID());
			changed = ps.executeUpdate();
			mysqldb.closePS(ps);
		}
		con.commit();
		mysqldb.closeConnection(con);
		return changed;
	}
}
